package cn.hellochaos.generator.controller;


import cn.hellochaos.generator.entity.User;
import cn.hellochaos.generator.entity.dto.ResultCode;
import cn.hellochaos.generator.util.CookieUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import cn.hellochaos.generator.entity.dto.ResultBean;
import cn.hellochaos.generator.service.FisheryService;
import cn.hellochaos.generator.entity.Fishery;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static cn.hellochaos.generator.entity.dto.ResultCode.*;


/**
 * <p>
 * 渔业资源相关表 前端控制器
 * </p>
 *
 * @author fmy
 * @since 2021-07-20
 * @version v1.0
 */
@Slf4j
@Api(tags = "渔业种质信息管理")
@CrossOrigin
@RestController
@RequestMapping("/fishery/api/v1/fishery")
public class FisheryController {

    @Resource
    private FisheryService fisheryService;

    /**
     * 查询分页数据
     * //to do ,增加校验
     */
    @ApiOperation("分页查询所有数据,可以按生物学分类编号，统一编号，中文名，英文名查询精确查询，" +
            "queryParameter1:[classificationId(生物学分类编号),queryId(统一编号),chineseName(中文名),englishName(英文名)],")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页号，默认1", defaultValue = "1", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，默认10", defaultValue = "10", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "queryParameter1", value = "查询参数名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "parameterValue1", value = "查询参数值", required = false, paramType = "query", dataType = "String"),
//            @ApiImplicitParam(name="chineseName",value="中文名",required=false,paramType="query",dataType="String"),
//            @ApiImplicitParam(name="englishName",value="英文名",required=false,paramType="query",dataType="String")
    })
    @ApiResponses({
            //code重复的情况下，第一个声明的生效。
            @ApiResponse(code = 204, message = "查询无结果"),
            @ApiResponse(code = 10002, message = "参数不全"),
            @ApiResponse(code = 10005, message = "请求参数的值非法")
    })
    @RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    // default "" 方便后面来写逻辑，""是未传参数的标志
    public ResultBean<?> listByPage(
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(name = "queryParameter1", defaultValue = "") String queryParameter1,
            @RequestParam(name = "parameterValue1", defaultValue = "") String parameterValue1,
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        //request.getServletContext().setAttribute("userName",user.getUsername());
        /*
        新增cookie变得有状态
         */


        //直接这样是生成一个新的sessionid

       // Cookie cookie = CookieUtil.getCookie("loginUserName");

          //  String cookieUsername = cookie.getValue();


        String userName = (String) request.getServletContext().getAttribute("userName");
        log.info("userName is {}", userName);
        Page<Fishery> fisheryPage = null;
        //注意正常分页的情况
        if (queryParameter1.equals("") && parameterValue1.equals("")) {
            // service直接返回一个不含参的page

            fisheryPage = fisheryService.listFisheryByPage(page, pageSize, queryParameter1, parameterValue1);
            //至少有一条数据
            int fisheryId = fisheryPage.getRecords().get(0).getFisheryId();
            Cookie cookie = CookieUtil.getCookie("fisheryId");
            if(cookie==null){
                cookie = new Cookie("fisheryId",Integer.toString(fisheryId));
            }else{
                cookie.setValue(Integer.toString(fisheryId));
            }
            cookie.setPath("/");
            response.addCookie(cookie);

            return new ResultBean<>(fisheryPage);
        }

        if (queryParameter1.equals("") || parameterValue1.equals("")) {
            return new ResultBean<>(MSG_PARAMS_NOT_COMPLETE, PARAMS_NOT_COMPLETE, null);
        }

        if (!queryParameter1.equals("classificationId") && !queryParameter1.equals("queryId") && !queryParameter1.equals("chineseName") && !queryParameter1.equals("englishName")) {
            return new ResultBean<>(MSG_PARAMS_VALUE_ERROR, PARAMS_VALUE_ERROR, null);
        }

        fisheryPage = fisheryService.listFisheryByPage(page, pageSize, queryParameter1, parameterValue1);

        int fisheryId = fisheryPage.getRecords().get(0).getFisheryId();
        Cookie cookie = CookieUtil.getCookie("fisheryId");
        if(cookie==null){
            cookie = new Cookie("fisheryId",Integer.toString(fisheryId));
        }else{
            cookie.setValue(Integer.toString(fisheryId));
        }
        cookie.setPath("/");
        response.addCookie(cookie);

        if (fisheryPage.getTotal() == 0) {
            return new ResultBean<>(MSG_NO_CONTENT, NO_CONTENT, null);
        }
        return new ResultBean<>(fisheryPage);
    }

    /**
     * 根据id查询
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = "application/json;charset=UTF-8")
    @ApiOperation("根据id查询渔业种质数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id的值", required = true, paramType = "path", dataType = "Integer")
    })
    public ResultBean<?> getById(@PathVariable("id") Integer id,HttpServletResponse response) {
        Fishery fishery = fisheryService.getFisheryById(id);
        if (fishery == null) {
            return new ResultBean<>(ResultCode.MSG_RESOURCE_NOT_FOUND, ResultCode.RESOURCE_NOT_FOUND);
        }
        Cookie cookie = CookieUtil.getCookie("fisheryId");
        if(cookie==null){
            cookie = new Cookie("fisheryId",Integer.toString(id));
        }else{
            cookie.setValue(Integer.toString(id));
        }
        cookie.setPath("/");
        response.addCookie(cookie);

        return new ResultBean<>(fishery);
    }

    /**
     * 新增
     */
    @ApiOperation("新增一条渔业种质数据")
    @RequestMapping(method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResultBean<?> insert(@RequestBody Fishery fishery) {
        return new ResultBean<>(fisheryService.insertFishery(fishery));
    }

    /**
     * 删除
     */
    @ApiOperation("删除一条渔业种质数据")
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = "application/json;charset=UTF-8")
    public ResultBean<?> deleteById(@PathVariable("id") Integer id) {
        int deletedId = fisheryService.deleteFisheryById(id);

        if (deletedId == -1) {
            return new ResultBean<>(MSG_RESOURCE_NOT_FOUND, RESOURCE_NOT_FOUND, null);
        }
        return new ResultBean<>(deletedId);
    }

    /**
     * 修改
     */
    @ApiOperation("更新一条渔业种质数据")
    @RequestMapping(method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public ResultBean<?> updateById(@RequestBody Fishery fishery) {
        int updatedId = fisheryService.updateFishery(fishery);

        if (updatedId == -1) {
            return new ResultBean<>(MSG_RESOURCE_NOT_FOUND, RESOURCE_NOT_FOUND, null);
        }
        return new ResultBean<>(updatedId);
    }
}
 